var addressCode = '';
var pick='';
var start = 1;
var selectObj = [];
var selectAllId = [];
var pageSize = 10;
var platformCategory="";
$(function () {
    "use strict";

    // startTime=getCurrentDate();

    if (orgClass == "org_ebb_city") {
        fillCounty("520600000000", "addressCode");
    } else {
        $("#hide-address").hide();
    }

    //选择地址下拉框后触发事件
    $("#addressCode").change(function () {
        addressCode = this.value;
        getTotalTransactionAmount();
        getUnablePickAmount();
        loadFarm();
    });


    $(".file").on("change", "input[type='file']", function () {
        if (orgClass != "org_ebb_county") {
            ShowTip("你还没有权限做该操作！请联系管理员", "success", 1000);
            setTimeout(function () {
                window.location = "index.html";
            }, 1000);
            return;
        }
        var filePath = $(this).val();
        if (filePath.indexOf("xls") != -1 || filePath.indexOf("xlsx") != -1) {
            $(".fileerrorTip").html("").hide();
            var arr = filePath.split('\\');
            var fileName = arr[arr.length - 1];

            $(".showFileName").html(fileName);

            $("#importbtn").removeAttr("display");
            $("#importbtn").attr("style", "display:inline");
        } else {
            $(".showFileName").html("");
            $(".fileerrorTip").html("您未上传文件，或者您上传文件类型有误！").show();
            return false
        }
    });
    var options = {
        url: '/ebb/ebb/import',
        type: 'post',
        success: function (data) {
            console.log(data);
            if (!data.error) {
                $("#importing").attr("style", "display:none");
                alert("导入成功!");
                self.location = 'ebbPlatform.html';
            } else {
                if (data.errorMessage) {
                    alert(data.errorMessage);
                }
            }
        },
        error: function (error) {
            var err = JSON.parse(error.responseText);
            alert(err.errorDescription);

        }
    };
    var lock = false;
    $("form[name=imporexcelform]").submit(function () {


        if (lock) {
            alert("不能重复提交");
            return;
        }
        lock = true;
        $(".btn-info").attr('disabled', true);
        ;
        $(this).ajaxSubmit(options);
        return false; //阻止表单默认提交
    });
    getTotalTransactionAmount();
    getUnablePickAmount();
    loadFarm();
    getPlatformCategory();
});
var totalSum = 0;
var storeName = "";
var startTime = "";
var endTime = "";
//导出平台信息
function exportTrainInfo() {
    window.location.href = "/ebb/business/export/?type=2" + "&storeName=" + storeName
        + "&addressCode=" + addressCode + "&startTime=" + startTime+"&platform="+platformCategory;
}

function getTotalTransactionAmount() {
    $.ajax({
        type: "get",
        url: "/ebb/admin/ebb/TransactionTotalAmount/?type=2&storeName=" + storeName + "&addressCode=" + addressCode +
        "&pick=" + pick + "&startTime=" + startTime + "&endTime=" + endTime+"&platformCategory="+platformCategory,
        contentType: "application/json",
        success: function (result) {
            var totalTradingVolume = 0;
            totalTradingVolume = parseFloat(result.totalTradingVolume).toFixed(2);
            $("#total-amount").text(totalTradingVolume);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.status == 401) {
                //跳转到登录页,带上登录后的跳转地址redirect_uri=???
                // redirect_login();
                ShowTip("你还没有登录，请先登录！", "success", 1000);
                setTimeout(function () {
                    window.location = "login.html";
                }, 1000);
            }
        }
    });
}


function getUnablePickAmount() {
    $.ajax({
        type: "get",
        url: "/ebb/admin/ebb/getUnPickAmountAdmin/?type=2&storeName=" + storeName + "&addressCode=" + addressCode + "&startTime=" + startTime + "&endTime=" + endTime,
        contentType: "application/json",
        success: function (result) {
            if(result>0){
                $("#show-hidden").show();
                var unablePick = result;
                $("#unable-pick").text(unablePick);
            }else{
                $("#show-hidden").hide();
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.status == 401) {
                //跳转到登录页,带上登录后的跳转地址redirect_uri=???
                // redirect_login();
                ShowTip("你还没有登录，请先登录！", "success", 1000);
                setTimeout(function () {
                    window.location = "login.html";
                }, 1000);
            }
        }
    });
}


function loadFarm() {
    $.ajax({
        type: "get",
        url: "/ebb/admin/ebb/list/?start=" + start + "&size=" + pageSize + "&type=2&storeName=" + storeName + "&addressCode=" +
        addressCode +"&pick=" + pick + "&startTime=" + startTime + "&endTime=" + endTime+"&platformCategory="+platformCategory,
        contentType: "application/json",
        dataType: "json",
        success: function (result) {
            if (typeof result != 'object') {
                result = eval('(' + result + ')');
            }
            if (result.data.length < 1) {
                $('#amount').text("0.00");
            }
            if (result.data.length > 0) {
                var totalCount = result.totalPages;
                totalPage = totalCount;
                $("#total-page").text(totalPage);

                $("#pagination-bar").show();
                $("#pagination-box").html('<ul id="pagination" class="pagination"></ul>');
                $('#pagination').twbsPagination({
                    totalPages: totalCount,
                    visiblePages: 5,
                    first: '第一页',
                    prev: '上一页',
                    next: '下一页',
                    last: '最后页',
                    onPageClick: function (event, page) {
                        start = page;
//                        params.index = emp;
                        $.ajax({
                            type: "get",
                            url: "/ebb/admin/ebb/list/?start=" + start + "&size=" + pageSize + "&type=2&storeName=" + storeName + "&addressCode=" + addressCode + "&pick=" + pick
                            +"&startTime=" + startTime + "&endTime=" + endTime+"&platformCategory="+platformCategory,
                            contentType: "application/json",
                            dataType: "json",
                            success: function (result) {
                                if (typeof result != 'object') {
                                    result = eval('(' + result + ')');
                                }
                                totalSum = result.totalPages;
                                var d = result.data;
                                var totalTradingVolumeByPage = 0;
                                for (var i = 0; i < d.length; i++) {
                                    totalTradingVolumeByPage += parseFloat(d[i].tradingVolume);
                                    if(d[i].platformCategoryParent==1){
                                        d[i].platformCategoryParent="网络零售平台";
                                    }else{
                                        d[i].platformCategoryParent="本地生活类服务平台";
                                    }

                                }
                                totalTradingVolumeByPage = totalTradingVolumeByPage.toFixed(2);
                                $('#amount').text(totalTradingVolumeByPage);
                                selectObj = d;
                                $("input[name='checkboxAll']").prop("checked", false);
                                selectAllId = [];
                                //渲染数据
                                $.templates("#farm-list-tmpl").link("#farm-list-data", d);
                                totalPages = result.totalPages;
                                $('#farm-count').text(result.totalCount);
                                $('#page-total').text(result.totalPages);
                                $('#page-index').val(page);
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                if (XMLHttpRequest.status == 401) {
                                    //跳转到登录页,带上登录后的跳转地址redirect_uri=???
                                    // redirect_login();

                                    ShowTip("你还没有登录，请先登录！", "success", 1000);
                                    setTimeout(function () {
                                        window.location = "login.html";
                                    }, 1000);
                                }


                            }
                        });
                    },
                    startPage: start
                });
            } else {
                $("#farm-list-data").html("<tr><td colspan='8'><h1 align='center' height='300px'>暂无数据</h1></td></tr>");
                $("#pagination-bar").hide();
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.status == 401) {
                //跳转到登录页,带上登录后的跳转地址redirect_uri=???
                // redirect_login();

                ShowTip("你还没有登录，请先登录！", "success", 1000);
                setTimeout(function () {
                    window.location = "login.html";
                }, 1000);
            }


        }
    });
}

function getPlatformCategory() {
    $("#platform-category").empty();
    $.ajax({
        type: "get",
        url: "/ebb/platform/category/?type=2",
        contentType: "application/json",
        success: function (result) {
            $("#platform-category").append("<option value=\"--请选择--\">--请选择--</option>");
            $.each(result,function(i,val){
                $("#platform-category").append('<option value='+val+'>'+val+'</option>');
            });
        }
    });
}

//获取当前系统年份月份
function getCurrentDate() {
    var date = new Date();
    var year = date.getFullYear();//年
    var mouth = date.getMonth() + 1;
    var day = date.getDate();
    //判断如果是1-9日期则加上0
    if (mouth >= 1 && mouth <= 9) {
        mouth = "0" + mouth;
    }
    var startTime = year + "-" + mouth;

    return startTime;
}

function selectall(obj) {
    selectAllId = [];
    //获取checked属性
    if ($(obj).prop("checked")) {
        //设置checked属性
        $("input[name='checkboxAll']").prop("checked", true);
        $("input[name='check']").prop("checked", true);
        for (var i = 0; i < selectObj.length; i++) {
            selectAllId.push(selectObj[i].id);
        }
    } else {
        //设置checked属性
        $("input[name='checkboxAll']").prop("checked", false);
        $("input[name='check']").prop("checked", false);
    }
}

function selectsub(id) {
    //获取checked属性
    if ($("#" + id).prop("checked")) {
        //设置checked属性
        $("input[id=id]").prop("checked", true);
        var count = 0;
        for (var i = 0; i < selectAllId.length; i++) {
            if (selectAllId[i] == id) {
                count += 1;
            }
        }
        if (count == 0) {
            selectAllId.push(id);
        }
    } else {
        //设置checked属性
        $("input[id=id]").prop("checked", false);
        for (var i = 0; i < selectAllId.length; i++) {
            if (selectAllId[i] == id) {
                selectAllId.splice(i, 1);
            }
        }
    }
    if (selectAllId.length == selectObj.length) {
        $("input[name='checkboxAll']").prop("checked", true);
    } else {
        $("input[name='checkboxAll']").prop("checked", false);
    }
}

function deleteSelectedAll() {
    if (selectAllId.length == 0) {
        ShowTip("请选择需要删除的项！", "danger", 1000);
        return;
    }
    if (orgClass != "org_ebb_county") {
        ShowTip("你还没有权限做该操作！请联系管理员", "success", 1000);
        return;
    }
    var ids = '';
    for (var i = 0; i < selectAllId.length; i++) {
        ids += "'" + selectAllId[i] + "'" + ","
    }
    ids = ids.substring(0, ids.length - 1);

    Showbox.Msg.confirm('如果有相关的产品，数据会一起删除，您确定删除所选记录吗？', function (v) {
        if (v == 'yes') {
            $.ajax({
                type: "delete",
                url: "/ebb/ebbDeleteSelectedAll/",
                contentType: 'application/json',
                data: ids,
                success: function (data, status) {
                    if (data > 0) {
                        var msg = "";
                        if (data > pageSize) {
                            msg = ",其中服务站数据" + pageSize + "条，相关产品" + (data - pageSize) + "条";
                        }
                        ShowTip("删除成功" + data + "条" + msg + "！", "success", 2000);
                        getTotalTransactionAmount();
                        getUnablePickAmount();
                        loadFarm();
                    } else {
                        ShowTip("删除失败！", "danger", 1000);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log(XMLHttpRequest);
                    ShowTip(XMLHttpRequest, "error", 1000);
                }
            });
        }
        if (v == 'no') {
        }
    });
}


function comments() {
    start=1;
    storeName = $("#name").val().trim();
    startTime = $("#startTime").val().trim();
    endTime = $("#endTime").val().trim();
    var addressCode1 = $("#addressCode").val();
    if (addressCode1 && addressCode1.trim() != "--选择区域--") {
        addressCode = $("#addressCode").val().trim();
    }
    var pick1=$("#pick-status").find("option:selected").val();
    if(pick1 && pick1.trim() != "--请选择--"){
        pick=$("#pick-status").find("option:selected").val().trim();
    }else{
        pick="";
    }
    var platform1 = $("#platform-category").find("option:selected").val();
    if(platform1!=""){
        if($("#platform-category").find("option:selected").val().trim()=="--请选择--"){
            platformCategory="";
            }
    }
    if(platform1&&platform1.trim()!="--请选择--"){
        platformCategory = $("#platform-category").find("option:selected").val().trim();
    }
    console.log(platformCategory);

//    var catName = $("#cate").val();
//    if (catName != "100000000000") {
//        params.enumCategoryId = catName;
//    }else{
//        params.enumCategoryId = "";
//    }
    getTotalTransactionAmount();
    getUnablePickAmount();
    loadFarm(storeName);
}


$('#go-index').click(function () {
    var index = $('#page-index').val();
    if (index > totalSum) {
        index = totalSum;
    }
    start = parseInt(index);
    getTotalTransactionAmount();
    getUnablePickAmount();
    loadFarm();
});
function deleteTrainInfo(id) {

    if (orgClass != "org_ebb_county") {
        ShowTip("你还没有权限做该操作！请联系管理员", "success", 1000);
        return;
    }
    Showbox.Msg.confirm('确定要删除该平台记录吗？', function (v) {
        if(v=="yes"){
            $.ajax({
                type: "DELETE",
                url: "/ebb/ebb/?id=" + id,
                dataType: "json",
                success: function (data) {
                    window.location.reload();
                }
            });
        }

    });

}

function exportBusinessTotal() {
    //  /ebb/business/total/export/
    window.location.href = "/ebb/business/total/export/?type=2&startTime=" + startTime + "&endTime=" + endTime;
}
function exportBusinessDetail() {
    //  /ebb/business/total/export/
    window.location.href = "/ebb/business/detail/export/?type=2&startTime=" + startTime + "&endTime=" + endTime;
}












